package com.joker.demo.controller;


import com.joker.demo.service.ChatAssistant;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentSplitter;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.splitter.DocumentSplitters;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.model.output.Response;
import dev.langchain4j.store.embedding.EmbeddingStore;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileNotFoundException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * 文件
 *
 * @author : feixiang.li
 * @since : 2025-09-26 13:40
 */
@RestController
@RequestMapping("/document")
public class DocumentController {


    @Resource
    ChatAssistant chatAssistant;

    @Resource
    private EmbeddingStore<TextSegment> embeddingStore;

    @Resource
    private EmbeddingModel embeddingModel;

    @RequestMapping("/add")
    public String add() throws FileNotFoundException {

        String filePath = "/Users/luckincoffee/Desktop/code/2025-09-07-canel/ai-roleplay-platform/demo/src/main/resources/阿里云面试总结及面试题详解.pdf";

        Path path = Paths.get(filePath);
        Document document = FileSystemDocumentLoader.loadDocument(path);
//        FileInputStream fileInputStream = new FileInputStream(filePath);
//       Document document = new ApacheTikaDocumentParser().parse(fileInputStream);
//        List<Document> documents = FileSystemDocumentLoader.loadDocuments(Paths.get(filePath), new TextDocumentParser());
//        //2.1 递归分割文档
        DocumentSplitter documentSplitter = DocumentSplitters.recursive(500, 100);
        List<TextSegment> segments = documentSplitter.split(document);
        int i = 0;
        for (TextSegment segment : segments) {
            Response<Embedding> embed = embeddingModel.embed(segment);
            embeddingStore.add(embed.content(), segment);
            System.out.println("第" + i + "个文档");
            i++;
        }
        return "成功加载";
    }


    @RequestMapping("/search")
    public String search() {
        String question = "阿里云面试问答有啥？";
        String chat = chatAssistant.chat(question);
        return chat;
    }
}
